package com.intelligy.util

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.intelligy.service.CAST_ACTION_UPDATE
import com.intelligy.service.KEY_MUSIC_INDEX
import com.intelligy.service.MUSIC_TIME_CURR
import com.intelligy.service.MUSIC_TIME_TOTAL
import java.io.IOException

class MusicUtil(val context: Context, private val musics: List<String>) {

    private val mediaPlayer: MediaPlayer = MediaPlayer()

    /**
     * 是否正在播放
     */
    var isPlaying: Boolean = false

    var index: Int = 0

    private val handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            val intent = Intent(CAST_ACTION_UPDATE)
            intent.putExtra(KEY_MUSIC_INDEX, index)
            intent.putExtra(MUSIC_TIME_CURR, mediaPlayer.currentPosition)
            intent.putExtra(MUSIC_TIME_TOTAL, mediaPlayer.duration)

            // 发送一条广播，通过前台界面，跟新播放状态
            context.sendBroadcast(intent)

            // handler 自己给自己发消息，以达到没 500ms 发送一条的效果
            sendEmptyMessageDelayed(1, 500)
        }
    }

    init {
        mediaPlayer.setOnCompletionListener {

        }
    }

    fun play() {
        mediaPlayer.start()
        isPlaying = true

        handler.sendEmptyMessage(1)
    }

    /**
     * 播放
     */
    fun play(index: Int) {
        this.index = index

        val music = musics[index]

        mediaPlayer.apply {
            reset()

            // 从网络读取文件
            setDataSource(context, Uri.parse(music))
            try {
                prepare()
            } catch (e: IOException) {
                context.toast("加载资源失败")
                return
            }
            start()
        }

        isPlaying = true

        // 让 Handler 去发送一个消息
        handler.sendEmptyMessage(0)
    }

    /**
     * 停止
     */
    fun stop() {
        mediaPlayer.stop()
        isPlaying = false
    }

    /**
     * 暂停
     */
    fun pause() {
        mediaPlayer.pause()
        isPlaying = false
    }

    /**
     * 下一曲
     */
    fun next() {
        if (index == musics.size - 1) index = 0
        else index++

        play(index)
    }

    /**
     * 上一曲
     */
    fun prev() {
        if (index == 0) {
            index = musics.size - 1
        } else {
            index--
        }
        play(index)
    }

    /**
     * 指定位置播放
     */
    fun playOnTime(position: Int) = mediaPlayer.seekTo(position)

}